<template>
	<a-card title="我的预约" :body-style="{ padding: '0' }">
		<!-- 预约状态筛选 -->
		<div class="select-container">
			预约状态：
			<a-select
				v-model:value="selectedStatus"
				placeholder="选择预约状态"
				style="width: 200px;"
				@change="handleStatusChange"
			>
				<a-select-option value="">全部</a-select-option>
				<a-select-option value="pending">待看房</a-select-option>
				<a-select-option value="rejected">已拒绝</a-select-option>
				<a-select-option value="expired">已过期</a-select-option>
			</a-select>
		</div>

		<!-- 预约列表表格 -->
		<a-table
			:columns="columns"
			:data-source="filteredAppointments"
			:pagination="false"
			:row-key="record => record.id"
			bordered
		>
			<template #bodyCell="{ column, record }">
				<!-- 房源图片 -->
				<template v-if="column.key === 'houseImage'">
					<img
						:src="record.houseImage"
						alt="房源图片"
						style="width: 110px; height: 86px; object-fit: cover"
					/>
				</template>
				<!-- 预约时间 -->
				<template v-else-if="column.key === 'appointmentDate'">
					{{ formatAppointmentDateRange(record) }}
				</template>
				<!-- 房源类型 -->
				<template v-else-if="column.key === 'houseType'">
					{{ record.houseType }}
				</template>
				<!-- 用户名称 -->
				<template v-else-if="column.key === 'userName'">
					{{ record.userName }}
				</template>
				<!-- 用户电话 -->
				<template v-else-if="column.key === 'userPhone'">
					{{ record.userPhone }}
				</template>
				<!-- 预约状态 -->
				<template v-else-if="column.key === 'appointmentStatus'">
					{{ getStatus(record.appointmentStatus) }}
				</template>
				<!-- 操作列：详情、拒绝 -->
				<template v-else-if="column.key === 'action'">
					<a @click="goToDetails(record.houseId)">详情</a>
					<!-- 只有状态为 pending 的预约显示拒绝按钮 -->
					<a v-if="record.appointmentStatus === 'pending'" style="margin-left: 1rem" @click="openRejectModal(record)">拒绝</a>
				</template>
				<!-- 默认展示 -->
				<template v-else>
					{{ record[column.dataIndex] }}
				</template>
			</template>
		</a-table>

		<!-- 分页器 -->
		<a-pagination
			class="pagination"
			:current="pagination.current"
			:page-size="pagination.pageSize"
			:total="pagination.total"
			:page-size-options="['5','10','20','50']"
			@change="handlePageChange"
			@showSizeChange="handlePageSizeChange"
			:show-total="(total, range) => `${range[0]}-${range[1]} 共 ${total} 条`"
			:locale="{ items_per_page: '条/页' }"
		></a-pagination>

		<!-- 拒绝 Modal -->
		<a-modal
			v-model:visible="rejectModalVisible"
			title="拒绝预约"
			:confirmLoading="rejectConfirmLoading"
			@ok="submitReject"
			@cancel="cancelReject"
			ok-text="确定"
			cancel-text="取消"
			width="400px"
		>
			<a-form layout="vertical">
				<a-form-item label="拒绝理由" required>
					<a-textarea
						v-model:value="rejectForm.remarks"
						placeholder="请输入拒绝理由"
						:rows="3"
					/>
				</a-form-item>
			</a-form>
		</a-modal>
	</a-card>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { message, Modal } from 'ant-design-vue';
import dayjs from 'dayjs';
import landlordApi from '@/api/landlordApi';

// 筛选状态
const selectedStatus = ref('');

// 预约数据与分页
const appointments = ref([]);
const pagination = reactive({
	current: 1,
	pageSize: 4,
	total: 0
});

// 表格列配置
const columns = [
	{ title: '房源图片', dataIndex: 'houseImage', key: 'houseImage', width: 120 },
	{ title: '预约时间', dataIndex: 'appointmentDate', key: 'appointmentDate', width: 110 },
	{ title: '房源类型', dataIndex: 'houseType', key: 'houseType' },
	{ title: '用户名称', dataIndex: 'userName', key: 'userName' },
	{ title: '用户电话', dataIndex: 'userPhone', key: 'userPhone' },
	{ title: '预约状态', dataIndex: 'appointmentStatus', key: 'appointmentStatus' },
	{ title: '操作', dataIndex: 'action', key: 'action' }
];

// 计算属性，根据 selectedStatus 筛选数据
const filteredAppointments = computed(() => {
	if (!selectedStatus.value) return appointments.value;
	return appointments.value.filter(item => item.appointmentStatus === selectedStatus.value);
});

const loadAppointments = () => {
	landlordApi.getAllAppointments(pagination.current, pagination.pageSize, selectedStatus.value)
		.then(res => {
			if (res.code === 200) {
				appointments.value = res.data.appointments;
				pagination.total = res.data.total;
			} else {
				message.error(res.message || '查询失败');
			}
		})
		.catch(() => {
			message.error('获取预约数据失败');
		});
};

const handlePageChange = (page) => {
	pagination.current = page;
	loadAppointments();
};

const handlePageSizeChange = (current, size) => {
	pagination.pageSize = size;
	pagination.current = 1;
	loadAppointments();
};

const handleStatusChange = (value) => {
	selectedStatus.value = value;
	pagination.current = 1;
	loadAppointments();
};

// 格式化预约时间
const formatAppointmentDateRange = (record) => {
	const startTime = dayjs(record.appointmentDate).format('YYYY-MM-DD HH:mm');
	const endTime = dayjs(record.appointmentDate).add(2, 'hour').format('HH:mm'); // 假设预约时长为2小时
	return `${startTime}-${endTime}`; // 显示为 "2025-03-20 11:00-13:00"
};

// 将后端英文状态转换为中文显示
const getStatus = (status) => {
	const map = {
		pending: '待看房',
		expired: '已过期',
		rejected: '已拒绝'
	};
	return map[status] || status;
};

// 详情按钮：跳转到房源详情页，带上房源id
const goToDetails = (houseId) => {
	window.open(`/house-details/${houseId}`, '_blank');
};

// ---------------------- 拒绝 Modal 相关 ----------------------
const rejectModalVisible = ref(false);
const rejectConfirmLoading = ref(false);
// 拒绝表单数据，用于记录当前预约ID和拒绝理由
const rejectForm = reactive({
	appointmentId: null,
	remarks: '' // 拒绝理由
});

// 点击“拒绝”按钮时，打开拒绝 Modal
const openRejectModal = (record) => {
	// 将当前预约ID传入拒绝表单
	rejectForm.appointmentId = record.id;
	// 清空之前的拒绝理由
	rejectForm.remarks = '';
	rejectModalVisible.value = true;
};

// 拒绝确认提交
const submitReject = () => {
	if (!rejectForm.remarks || rejectForm.remarks.trim() === '') {
		message.error('请填写拒绝理由');
		return;
	}
	// 弹出最终确认 Modal
	Modal.confirm({
		title: `确定拒绝该预约吗？`,
		okText: '确定',
		cancelText: '取消',
		onOk() {
			rejectConfirmLoading.value = true;
			// 调用后端接口更新预约状态为拒绝，同时传递拒绝理由
			landlordApi.auditAppointment({
				appointmentId: rejectForm.appointmentId,
				appointmentStatus: 'rejected',
				remarks: rejectForm.remarks,
			})
				.then(res => {
					rejectConfirmLoading.value = false;
					if (res.code === 200) {
						message.success('拒绝成功');
						rejectModalVisible.value = false;
						loadAppointments();
					} else {
						message.error(res.message || '拒绝失败');
					}
				})
				.catch(() => {
					rejectConfirmLoading.value = false;
					message.error('拒绝失败，请重试');
				});
		}
	});
};

// 取消拒绝操作
const cancelReject = () => {
	rejectModalVisible.value = false;
};

onMounted(() => {
	loadAppointments();
});
</script>

<style scoped>
.select-container {
	display: flex;
	justify-content: flex-end;
	align-items: center;
	margin-bottom: 1rem;
	font-size: 15px;
}
.select-container > *:not(:last-child) {
	margin-right: 8px;
}
.pagination {
	margin-top: 1rem;
	text-align: right;
}
</style>
